package m.store.action;

import m.base.action.BaseAction;
import m.base.util.LevelUtil;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.common.model.util.QueryOrder;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.form.*;
import m.html.list.*;
import m.store.model.OrderRepositoryCheck;
import m.store.service.OrderRepositoryCheckService;
import m.store.util.ColorUtil;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.StringUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@ActionMeta(name = "store/orderRepositoryCheck")
public class OrderRepositoryCheckAction extends BaseAction {
    private OrderRepositoryCheck model;
    private List<OrderRepositoryCheck> getCheckList(String orderOid,Object[] oids) throws Exception {
        List<QueryCondition> cl=new ArrayList<>();
        if(!StringUtil.isSpace(orderOid)) cl.add(QueryCondition.eq("orderOid",orderOid));
        if(null!=oids) cl.add(QueryCondition.in("oid",oids));
        return ModelQueryList.getModelList(OrderRepositoryCheck.class,new String[]{"*","goods.*","stockRecord.*"},null,
            QueryCondition.and(
                QueryCondition.or(cl.toArray(new QueryCondition[0])),
                QueryCondition.eq("checkUser.oid", PowerUtil.getSessionUserOid()),
                QueryCondition.eq("status",OrderRepositoryCheck.Status_Check)
            )
        );
    }
    @RequestMeta(logTitle = "仓库审核",logDescription = "仓库审核订单明细",transaction = true,params = {"orderOid","list"})
    public JSONMessage doCheck(String orderOid,String[] list) throws Exception {
        PowerUtil.verifyPower(PowerUtil.Stock);
        getService(OrderRepositoryCheckService.class).check(getCheckList(orderOid,list),model.getStatus(),model.getCheckRemark());
        return JSONMessage.success("操作成功");
    }

    @RequestMeta(params = {"orderOid","list"})
    public VueResult toCheck(String orderOid,String[] list) throws Exception {
        List<OrderRepositoryCheck> ls=getCheckList(orderOid,list);
        model=new OrderRepositoryCheck();
        model.setStatus(OrderRepositoryCheck.Status_Yes);
        ModelForm form = new ModelForm("仓库审核");
        form.addItem(
            FormInput.radio("审核结果", "model.status", "@Y:通过,N:不通过"),
            FormInput.input("审核备注", "model.checkRemark").setSpan(2).setPlaceholder("请输入审核备注")
        )
        .addData("model",model)
        .addData("orderOid", StringUtil.noSpace(orderOid,""))
        .addData("list",null!=list?list:new String[0])
        .addButton(
            FormButton.pri("提交","doCheck").setConfirm("确定要提交吗？")
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doCheck",actionUrl("doCheck"),"{orderOid:this.orderOid,list:this.list,model:this.model}")
                .success("backFlag")
        );
        TableForm table=new TableForm("审核商品明细");
        table.setData("ls",ls);
        table.addColumn(
            TableColumn.index("序号"),
            TableColumn.text("类型","orderType",100,"m.store.model.OrderRepositoryCheck!orderType")
                .setShow(ListElement.tag("m.store.model.OrderRepositoryCheck!orderType", ColorUtil.getOrderType(),false)),
            TableColumn.text("商品","goods.name",200),
            TableGroup.ins("登记信息",
                TableColumn.number("单价","price",100),
                TableColumn.number("数量","num",100),
                TableColumn.number("总优惠","preferential",100)
            ),
            TableGroup.ins("优惠后",
                TableColumn.number("金额","amount",100),
                TableColumn.number("单价","preferentialPrice",100)
            ),
            TableColumn.text("备注","remark",200)
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form).addForm(table);
    }
    public VueResult viewList() throws Exception {
        VueListResult result=getVueListResult("订单商品审核",OrderRepositoryCheck.class,actionUrl("viewList"));
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addCol(toTextColumn("仓库", "repository.name", 100, true));
        result.addCol(toTextColumn("商品名称", "goods.name", 100, true));
        result.addCol(toNumberColumn("单价", "price", 100, true).setGroupTitle("登记信息"));
        result.addCol(toIntegerColumn("数量", "num", 100, true).setGroupTitle("登记信息"));
        result.addCol(toNumberColumn("总优惠", "preferential", 100, true).setGroupTitle("登记信息"));
        result.addCol(toNumberColumn("金额", "amount", 100, true).setGroupTitle("优惠后"));
        result.addCol(toNumberColumn("单价", "preferentialPrice", 100, true).setGroupTitle("优惠后"));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        result.addCol(toStatusColumn());
        result.addCol(toTextColumn("审核人", "checkUser.realname", 100, true));
        result.addCol(toTextColumn("审核备注", "checkRemark", 100, true));
        result.addCol(toDateColumn("审核时间", "checkDate", 100, true));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("orderOid",getParamsValue("orderOid")));
        return result;
    }
    protected ListColumn toOrderTypeColumn(){
        String dict="m.store.model.OrderRepositoryCheck!orderType";
        return toElementColumn("订单类型", "orderType", 100,
                ListElement.tag(dict, ColorUtil.getOrderType(),false)
        ).setAlign(Align.CENTER).setFilter(true).setDictType(dict);
    }
    protected ListColumn toStatusColumn(){
        String dict="m.store.model.OrderRepositoryCheck!status";
        return toElementColumn("状态", "status", 100,
                ListElement.dot(dict, ColorUtil.getRepositoryCheckStatus())
        ).setAlign(Align.CENTER).setFilter(true).setDictType(dict);
    }
    /*
     * 订单商品审核列表
     */
    public VueResult checkList() throws Exception {
        VueListResult result=getVueListResult("订单商品审核",OrderRepositoryCheck.class,actionUrl("checkList"));
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setHeight(-1);
        result.setSelection("oid",false);
        result.setSelectionDisabled("record.status!='"+OrderRepositoryCheck.Status_Check+"'");
        result.setMergeCellsInfo(1,4);
        result.setFocusRefresh(true);
        result.addCol(toIndexColumn());
        result.addCol(toLinkColumn("订单单号", "orderNo", 100, true,
            new ListEvent(actionUrl(OrderModelAction.class,"toViewOrder"), EventType.MODAL,1200)
                .addParam("oid","orderOid").addParam("orderNo","orderNo")
        ));
        result.addCol(toDateColumn("订单账期", "orderDate", 100, true));
        result.addCol(toSpaceColumn("按订单", 90,
            ListElement.test("record.status=='"+OrderRepositoryCheck.Status_Check+"'",
                ListButton.modal("审核", ButtonType.PRIMARY,actionUrl("toCheck"),1000, SuccessMethod.REFRESH)
                    .addParam("orderOid","orderOid")
            )
        ));
        result.addCol(toOrderTypeColumn());
        result.addCol(toTextColumn("仓库", "repository.name", 100, true));
        result.addCol(toLinkColumn("商品名称", "goods.name", 100, true,
            new ListEvent(actionUrl(StoreGoodsAction.class,"toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toNumberColumn("单价", "price", 100, true).setGroupTitle("登记信息"));
        result.addCol(toIntegerColumn("数量", "num", 100, true).setGroupTitle("登记信息"));
        result.addCol(toNumberColumn("总优惠", "preferential", 100, true).setGroupTitle("登记信息"));
        result.addCol(toNumberColumn("金额", "amount", 100, true).setGroupTitle("优惠后"));
        result.addCol(toNumberColumn("单价", "preferentialPrice", 100, true).setGroupTitle("优惠后"));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        result.addCol(toStatusColumn());
        result.addCol(toTextColumn("审核备注", "checkRemark", 100, true));
        result.addCol(toDateColumn("审核时间", "checkDate", 100, true));
        result.addCol(toSpaceColumn("按商品", 90,
            ListElement.test("record.status=='"+OrderRepositoryCheck.Status_Check+"'",
                ListButton.modal("审核", ButtonType.PRIMARY,actionUrl("toCheck"),1000, SuccessMethod.REFRESH)
                    .addParam("list[]","oid")
            )
        ).setFixed(Align.RIGHT));
        result.addButton(
            ListButton.modal("批量审核", ButtonType.PRIMARY,actionUrl("toCheck"),1000, SuccessMethod.REFRESH)
                .addParam("","oid")
        );
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("checkUser.oid", PowerUtil.getSessionUserOid()));
        result.addOrder(
            QueryOrder.desc("orderDate")
        );
        return result;
    }

    public OrderRepositoryCheck getModel() {
        return model;
    }

    public void setModel(OrderRepositoryCheck model) {
        this.model = model;
    }
}
